class Coupon extends React.Component {
    constructor(props) {
        super(props);
        //threshold,type,clicknew,name,precent
        this.state = {
            name: '',
            type: '0',
            clicknew: !1,
            thresholdtype: 0,
            describe:'',
            reduce:0,

        };
    }




    componentDidMount() {
        let id = GetQueryString('id');
        if(id=='null'){
            // let def_startDate = formatDate1(new Date());
            // console.log(def_startDate);
            
            // this.setState({def_startDate,def_endDate:formatDate1(new Date())})
        }
        this.freshlist();
    }

    freshlist() {
        let that =this;
       getcoupons(res=>{
           if(res.issuccess==1){
            var listhtml = [];
            res.list.forEach((x,i) => {
                let zhe = x.percents%10==0?x.percents/10:parseFloat(x.percents/10).toFixed(1), yhxs = x.type==0
                ?(x.threshold==0?`全场减${x.reduce/100}元`:`满${x.threshold/100}减${x.reduce/100}元`)
                :(x.threshold==0?`全场${zhe}折`:`满${x.threshold/100}打${zhe}折`),
                time = formatDate1(new Date(x.startDate))+' -- '+formatDate1(new Date(x.endDate))
                listhtml.push(
                    <tr key={i}>
                        <td>{x.name}</td>
                        <td>{yhxs}</td>
                        <td>{time}</td>
                        <td className='operate'>
                        <p className='edit' onClick={this.edit.bind(this,i)}>编辑</p>
                        <p onClick={this.del.bind(this,x.id)}>删除</p>
                        </td></tr>
                )
            });
            this.setState({list:res.list,listhtml})
           }
       },1)
    }
    add() {
        this.setState({ clicknew: !0 })
    }
    inputchange(name,e) {
        console.log('name',name)
        this.setState({[name]:e.target.value})
    }
  
    typechange(e) {
        this.setState({ type: e })
    }
    thresholdtypechange(e) {
        this.setState({ thresholdtype: e })
    }
    datechange(i,e){
        let prop = `${i==0?'start':'end'}Date` ;
        this.setState({[prop]:e.target.value})
    }
    submit() {
        let { type,count, name, thresholdtype, startDate,id,endDate,describe,percents,reduce,threshold } = this.state, err = ''
        ,data={
            describe,
            type,
            id,
            endDate:Number(new Date(endDate+' 00:00:00')),
            threshold:isNaN(parseInt(threshold))?0:parseInt(threshold),
            startDate:Number(new Date(startDate+' 00:00:00')),
            precent:isNaN(parseInt(percents))?0:parseInt(percents),
            count: isNaN(parseInt(count))?0:parseInt(count) ,
            reduce:isNaN(parseInt(reduce))?0:parseInt(reduce),
            name
        },that = this;
        if(!id||id==-1) delete data.id;
        if(thresholdtype==0) delete data.threshold; 
        if(describe.length==0) err='请填写优惠券描述'
        if(data.endDate<data.startDate) err='失效日期不能小于生效日期'
        if(isNaN(data.endDate)) err='请选择失效日期'
        if(isNaN(data.startDate)) err='请选择生效日期'
        if(thresholdtype==1&&(threshold<=0||isNaN(threshold))) err='使用门槛金额必须大于0'
        if(type==0&&(reduce<=0||isNaN(reduce))) err='指定现金必须大于0'
        if(type==1&&(percents<=0||isNaN(percents))) err='折扣必须大于0'
        if(parseInt(count)<0||isNaN(count)) err='发放数量有误'
        if(name.length==0) err='请填写优惠券名称'
      
        console.log( data ,'submit');

        if(err.length>0) {
            alert(err)
            return;
        }

        aoecoupon(data,res=>{
            if(res.issuccess==1){
                alert(`${!id?"添加":"修改"}成功`);
                that.freshlist()
            }
        })
        //date=Number(new Date(+' 00:00:00'))

        


        // if (!finishupload) err = '请先上传图片';
        // if (name.length == 0) err = '请填写分类名称';
        // if (err.length > 0) {
        //     alert(err);
        //     return;
        // }
        // var data = { src: thumburl, name };
        // if (Number(this.state.id) > 0) {
        //     data['id'] = this.state.id;
        // }
        // addcategory(data, res => {
        //     if (res.issuccess == 1) {
        //         var text = Number(this.state.id) > 0 ? '修改成功' : '添加成功'
        //         alert(text)
        //         this.setState({
        //             clicknew: !1,
        //             finishupload: !1,
        //             name: '',
        //             thumburl: ''
        //         })
        //         this.freshlist();
        //     }
        // })
    }

    edit(e) {
        var {name,threshold,describe,startDate,endDate,type,count,id,reduce} = this.state.list[e],thresholdtype=threshold==0?0:1;
        if(type==0) this.setState({reduce:Number(reduce)/100})
        console.log(this.state.list[e].percents,'this.state.list[e].percents');
        
        if(type==1) this.setState({percents:this.state.list[e].percents})
        startDate = formatDate1(new Date(startDate));
        endDate = formatDate1(new Date(endDate));
     //   endDate = Date.parse(endDate)

        this.setState({id,name,threshold:threshold/100,describe,startDate,endDate,thresholdtype,type,clicknew:!0,count,isedit:!0})
        // list.forEach(x => {
        //     if (x.id == e) {
        //         this.setState({
        //             thumburl: x.picpath,
        //             name: x.name,
        //             id: x.id,
        //             clicknew: !0,
        //             finishupload: !0,

        //         })
        //     }
        // });
    }
    del(e) {
        this.setState({ delid: e })
        $('#myModal').modal('toggle');
    }

    confirmdel() {
        let that = this;
        delcoupon(that.state.delid,res=>{
            if(res.issuccess==1){
                alert('删除成功');
                $('#myModal').modal('toggle');
                that.freshlist()
            }
        })

    }
    cancel(){
        this.setState({clicknew:!1,id:-1})
    }


    render() {
        let { threshold, thresholdtype, type,describe,count, clicknew, name, percents, reduce,startDate,endDate } = this.state;
        console.log(reduce,'reduce');
        

        return (

            <div className='content_wrap panel-default content_wrap'>
                <Modal content='确定删除吗？' click={this.confirmdel.bind(this)} />
                <div className='breadLine '>
                    当前位置 > 优惠券管理
                        </div>
                <div className='inputs panel-body'>
                    <h3>优惠券管理</h3>
                    <button style={{ display: clicknew ? "none" : "" }} onClick={this.add.bind(this)} className='btn add btn-primary center' >新建优惠券</button>
                    <div style={{ display: clicknew ? "" : "none" }}>
                        <div className="input-group input-group">
                            <span className="input-group-addon ">名称</span>
                            <input id='name' onChange={this.inputchange.bind(this, 'name')} type="text" value={name} placeholder='请输入优惠券名称' className="form-control " />
                        </div>

                        <div className="input-group input-group count">
                            <span className="input-group-addon ">发放数量</span>
                            <input id='count' onChange={this.inputchange.bind(this, 'count')} type="text" value={count} placeholder='请输入发放数量' className="form-control " />
                            <p style={{margin:0}} className='center'>张（0为无限制）</p>
                        </div>

                        <div className="input-group input-group radios">
                            <span className="input-group-addon">优惠形式</span>
                            <div>
                                <label className="radio-inline mj">
                                    <input type="radio" id="inlineCheckbox" 
                                    onChange={this.typechange.bind(this, 0)} checked={type == 0} value="0" />
                                    <p>指定现金</p> 
                                    <input style={{display:type == 0?'':'none'}} className="form-control " onChange={this.inputchange.bind(this, 'reduce')} value={reduce} />
                                    <p style={{display:type == 0?'':'none'}}>元</p> 
                                    
                                </label>
                                <label className="radio-inline mj">
                                    <input type="radio" id="inlineCheckbox" onChange={this.typechange.bind(this, 1)}
                                     checked={type == 1} value="1" /> 
                                     <p>打折</p>
                                    <input style={{display:type == 1?'':'none'}}  className="form-control " onChange={this.inputchange.bind(this, 'percents')} value={percents} />
                                    <p style={{display:type == 1?'':'none'}}> (0-100的百分比整数)</p>
</label>
                            </div>
                        </div>

                        <div className="input-group input-group radios">
                            <span className="input-group-addon ">使用门槛</span>
                            <div>
                                <label className="radio-inline">
                                    <input type="radio" id="inlineCheckbox" onChange={this.thresholdtypechange.bind(this, 0)} checked={thresholdtype == 0} value="0" />
                                    无限制
                                    </label>

                                <label className="radio-inline mj">
                                <input type="radio" id="inlineCheckbox" onChange={this.thresholdtypechange.bind(this, 1)}
                                 checked={thresholdtype == 1} value="1" />
                                  <p style={{display:thresholdtype == 1?'none':''}}>满减</p>
                                 <div style={{display:thresholdtype == 1?'flex':'none'}} >
                                 <p >满</p>
                                    <input id='threshold' onChange={this.inputchange.bind(this, 'threshold')}
                                        type="text" value={threshold} placeholder='满减金额' className="form-control " />
                                        <p >元可使用</p>
                                 </div>
                                    </label>
                            </div>

                        </div>

                        <div className="input-group input-group">
                            <span className="input-group-addon ">生效时间</span>
                            <input type='date' onChange={this.datechange.bind(this,0)}   value={startDate}/>
                        </div>
                        <div className="input-group input-group">
                            <span className="input-group-addon ">失效时间</span>
                            <input type='date' onChange={this.datechange.bind(this,1)}   value={endDate}/>
                        </div>
                        <div className="input-group input-group ">
                            <span className="input-group-addon desc">商品描述</span>
                            <textarea id='describe' 
                            onChange={this.inputchange.bind(this, 'describe')} 
                            value={describe} 
                            style={{ height: "30vh" }} className="form-control" placeholder='请输入优惠券描述' rows="3"></textarea>
                        </div>

                        <button onClick={this.submit.bind(this)} className='btn submit btn-primary center ' >确定{this.state.isedit?"修改":"添加"}</button>
                        <button onClick={this.cancel.bind(this)} className='btn submit btn-primary center ' >取消</button>
                    </div>

                    <table className="table table-hover">
                        <thead>
                            <tr>
                                <th>优惠券名称</th>
                                <th>优惠形式</th>
                                <th>活动时间</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            {this.state.listhtml}
                        </tbody>
                    </table>

                </div>
            </div>
        )
    }
}





ReactDOM.render(
    <div>
        <TopLine />
        {/* <LeftMenu code='5' /> */}
        <LeftMenu code='coupon' />
        <Coupon />
    </div>
    //<Barrage/>
    , $('.container')[0]
)